package cn.stylefeng.roses.seata.demo.order.modular.service.impl;

import cn.stylefeng.roses.seata.demo.order.modular.entity.OrderTbl;
import cn.stylefeng.roses.seata.demo.order.modular.mapper.OrderTblMapper;
import cn.stylefeng.roses.seata.demo.order.modular.service.OrderTblService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 业务实现层
 *
 * @author stylefeng
 * @date 2021/08/29 10:33
 */
@Service
@Slf4j
public class OrderTblServiceImpl extends ServiceImpl<OrderTblMapper, OrderTbl> implements OrderTblService {

    /**
     * 用户的账户id，用来扣减用户的余额
     */
    private static final String USER_ID = "U100001";

    @Resource
    private RestTemplate restTemplate;

    @Override
    public void placeOrder(String userId, String commodityCode, int orderCount) {
        // 计算订单金额
        int orderMoney = calculate(commodityCode, orderCount);

        // 扣减用户金额
        invokerAccountService(orderMoney);

        // 创建订单实体
        final OrderTbl order = new OrderTbl();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(orderMoney);

        // 插入实体
        this.save(order);
    }

    /**
     * 计算订单金额，随机金额
     *
     * @author fengshuonan
     * @date 2021/8/29 10:49
     */
    private int calculate(String commodityId, int orderCount) {
        return orderCount * 10;
    }

    /**
     * 调用account服务，扣减用户账户的余额
     *
     * @author fengshuonan
     * @date 2021/8/29 10:52
     */
    private void invokerAccountService(int orderMoney) {

        String url = "http://127.0.0.1:18084/account";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

        map.add("userId", USER_ID);
        map.add("subMoney", orderMoney + "");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
        log.info("收到account响应信息," + response);
    }

}